import file from '@system.file';
import request from '@ohos.request';
import fetch from '@system.fetch';
import router from '@system.router';
import prompt from '@system.prompt';
import geolocation from '@system.geolocation';
import Service from '../../generated/TestService.js';
import dataStorage from '@ohos.data.storage'
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import featureAbility from '@ohos.ability.featureAbility';
import http from '@ohos.net.http';
import fileio from '@ohos.fileio';

export default {
    data: {
        context:'',
        path:'',
        cachepath:null,
        imageName:null,
        imagePath:null,
        userid:null,
        username:null,
        password:null,
        email:null,
        headshot:null,
        sex:null,
        phonenumber:null,
        picturename:null,
    },
    async onInit(){
        this.context = featureAbility.getContext()
        this.path = await this.context.getFilesDir()
        this.cachepath = await this.context.getCacheDir()
    },
    async onShow(){
        this.context = featureAbility.getContext();
        this.path = await this.context.getFilesDir();
        let storage = dataStorage.getStorageSync(this.path + '/mystore')
        this.userid = storage.getSync('userid','-1');
        this.username = storage.getSync('username', '未登录')
        this.password = storage.getSync('password', '-1')
        this.email = storage.getSync('email', '-1')
        this.headshot = storage.getSync('headshot', '-1')
        this.sex = storage.getSync('sex', '-1')
        this.phonenumber = storage.getSync('phonenumber', '-1')
    },
    TurnBack(){
        router.back();
    },
    LogOut(){
        let storage = dataStorage.getStorageSync(this.path + '/mystore')
        storage.putSync('userid', '-1')
        storage.putSync('username', '未登录')
        storage.putSync('password', '-1')
        storage.putSync('email', '-1')
        storage.putSync('headshot', '/common/picture/initheadshot.png')
        storage.putSync('sex', '-1')
        storage.putSync('phonenumber', '-1')
        storage.flushSync()
        router.back()
    },
    ChooseHeadshot(){
        let storage = dataStorage.getStorageSync(this.path + '/mystore')
        this.userid = storage.getSync('userid', '-1')
        if(this.userid === '-1'){
            prompt.showToast({
                message: '请先登录'
            })
            return;
        }

        var that = this
        let option = {type : "image", count : 1  };
        mediaLibrary.getMediaLibrary().startMediaSelect(option).then((value) => {
            console.log("Media resources selected."+value);             // Obtain the media selection value.
            // 使用calculate同步方法，返回OperateData对象。
            this.utilInterface = createLocalParticleAbility('edu.zut.hys.jsskateboard.util.UtilServiceAbility');
            this.utilInterface.CopyToCache(value[0],result => {
                console.info(this.lable+result)
                that.imageName = result;
                that.imagePath = "internal://cache/"+result;
                prompt.showToast({
                    message: '选择成功'
                })
                that.UploadImage();
            })
        }).catch((err) => {
            console.log("An error occurred when selecting media resources.");
            prompt.showToast({
                message: '选择失败'
            })
        });
    },
    UploadImage(){
        var that = this
        if(this.imageName!==null)
        request.upload({ url: 'http://101.35.82.76:9001/upload',
            files:[{
                       filename: this.imageName,
                       name:'file',
                       uri:'internal://cache/'+this.imageName,
                       type:'png',
                   }],
            data:[{name:"userid",value:this.userid}]
        },
            (err, data) => {
                if (err) {
                    prompt.showToast({
                        message: '上传失败'
                    })
                    console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
                    return;
                }
                prompt.showToast({
                    message: '上传成功'
                })
                setTimeout(that.ChangeHeadshot(),2000);
            });
    },
    ChangeHeadshot(){
        var that = this

        let httpRequest= http.createHttp();
        httpRequest.request("http://101.35.82.76:9002/user/changeHeadshot?userid="+this.userid,
            {
                method: 'GET',
                readTimeout: 60000,
                connectTimeout: 60000
            },(err, data) => {
                if (!err) {
                    console.info('Result:' + data.result);
                    console.info('code:' + data.responseCode);
                    console.info('header:' + data.header);
                    var res = JSON.stringify(JSON.parse(data.result).data)
                    var headshot = JSON.stringify(JSON.parse(res).headshot)
                    this.headshot = JSON.parse(headshot)
                    prompt.showToast({
                        message: '更改成功'
                    })
                } else {
                    console.info('error:' + err.data);
                    prompt.showToast({
                        message: 'Send Error'+ JSON.stringify(err)
                    })
                }
            });
    },
    DownloadFile(){
        //internal://share/
        this.picturename = 'wutiaowu.png'
        request.download({ url: 'http://101.35.82.76:9001/file/picture/'+this.picturename},
            (err, data) => {
                if (err) {
                    console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
                    return;
                }
                prompt.showToast({
                    message: data
                })
                data.on('progress', this.download_callback);

            });
    },
    download_callback(receivedSize, totalSize) {
        console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
        var that = this;
        if(receivedSize>=totalSize){
            prompt.showToast({
                message: '开始复制'
            })
//            fileio.copyFileSync('internal://cache/'+this.picturename, 'internal://Download/'+this.picturename);
            this.utilInterface = createLocalParticleAbility('edu.zut.hys.jsskateboard.util.UtilServiceAbility');
            this.utilInterface.SavePicture('internal://cache/'+this.picturename,result => {
                console.info(this.lable+result)

            })
        }
    },
}
